//
//  JCLTestViewController.swift
//  WeiBo
//
//  Created by DDC on 2017/9/22.
//  Copyright © 2017年 DDC. All rights reserved.
//

import UIKit
import SVProgressHUD
/// 如果XIB同控制器的名称相同,首先加载的是xib而不是控制器
class JCLTestViewController: UIViewController {
    
    
    /// 底部工具栏底部约束
    @IBOutlet weak var toolbarBottomCons: NSLayoutConstraint!
    
    // 工具栏
    @IBOutlet weak var toolbar: UIToolbar!
    // textView
    @IBOutlet weak var textView: JCLTextView!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setUpUI()
        
    }
    /// 激活键盘 
    ///
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        textView.becomeFirstResponder()
    }
    /// 关闭按钮点击的时候, 关闭键盘
    /// 取消第一响应者
    /// - Parameter animated: 动画
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        textView.resignFirstResponder()
    }
    // 自定义导航栏发布按钮属性
    lazy var commitBtn:UIButton = {
       
        let btn = UIButton()
        btn.setTitle("发布", for: [])
        btn.setTitleColor(UIColor.gray, for: .disabled)
        btn.setTitleColor(UIColor.orange, for: [])
        btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15)
        btn.addTarget(self, action: #selector(commitStatus), for: .touchUpInside)
        btn.sizeToFit()
        
        return btn
    }()
    
    // 移除通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
}


fileprivate extension JCLTestViewController {

    /// 设置界面
    func setUpUI () {
        view.backgroundColor = UIColor.white
        // 退出按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", fontSize: 15, taret: self, action: #selector(clickBack))
        // 发布按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: commitBtn)
        commitBtn.isEnabled = false 
        // 头部收缩
        textView.contentInset.top = 64
        //监听键盘收缩的通知
        NotificationCenter.default.addObserver(self, selector: #selector(toolbarAndKeyboardChange), name: .UIKeyboardWillChangeFrame, object: nil)
        
        setupToolBar()
    }
    /// 设置工具栏
    func setupToolBar () {
        
        let itemSettings = [["imageName":"toolbar-image"],
                            ["imageName":"toolbar-contact","actionName":"emoticonKeyboard"],
                            ["imageName":"toolbar-jing"],
                            ["imageName":"toolbar-@"],
                            ["imageName":"toolbar-add"]]
        
        var items = [UIBarButtonItem]()
        for item in itemSettings {
            
            guard let imageName = item["imageName"] else {
                continue
            }
            
            let image = UIImage(named: imageName)
            let btn = UIButton()
            btn.setImage(image, for: [])
            btn.sizeToFit()
           
            if let actionName = item["actionName"] {
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }
            // 追加按钮到toolbar
            items.append(UIBarButtonItem(customView: btn))
            // 添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
            
        }
        // 删除最后一个item弹簧
        items.removeLast()
        toolbar.items = items
    }
    @objc func emoticonKeyboard () {
        
    let keyboardView = JCLEmoticonInputView.inputView { (emoticon) in
        
         self.textView.insertEmoticon(emo: emoticon)
        }
        textView.inputView = textView.inputView == nil ? keyboardView : nil
     
        // textView的输入助理视图(可以制作纯代码创建toolbar的方法)
        /*
         
         let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 100, height: 44))
         toolbar.backgroundColor = UIColor.lightGray
         textView.inputAccessoryView = toolbar
         
         */
        // 刷新视图
        textView.reloadInputViews()
    }
    
    /// 发布微博信息
    @objc func commitStatus () {
        
        print("发布微博")
        // 获取发布微博的文本
        // 添加发送微博的表情文本属性
        let text = textView.emoticonString
        /// FIXME
        // 发布微博--(由于官方关闭了发送微博的接口,故无法测试)
        let image = UIImage(named: "toolbar-image")
        JCLNetWorkTools.shared.postStatus(text: text, image: image) { (result, isSuccess) in
            
            print(result)
            let message = isSuccess ? "发布成功" : "网络不给力"
            SVProgressHUD.showInfo(withStatus: message)
        }

    }
    
    /// 退出按钮
    @objc func clickBack()  {
        self.dismiss(animated: true, completion: nil)
    }
    /// 键盘监听方法
    ///
    /// - Parameter n: 通知
    @objc func toolbarAndKeyboardChange(n:Notification) {
        
        print(n.userInfo)
        /*
         Optional([AnyHashable("UIKeyboardCenterBeginUserInfoKey"): NSPoint: {207, 871.5}, AnyHashable("UIKeyboardIsLocalUserInfoKey"): 1, AnyHashable("UIKeyboardCenterEndUserInfoKey"): NSPoint: {207, 600.5}, AnyHashable("UIKeyboardBoundsUserInfoKey"): NSRect: {{0, 0}, {414, 271}}, AnyHashable("UIKeyboardFrameEndUserInfoKey"): NSRect: {{0, 465}, {414, 271}}, AnyHashable("UIKeyboardAnimationCurveUserInfoKey"): 7, AnyHashable("UIKeyboardFrameBeginUserInfoKey"): NSRect: {{0, 736}, {414, 271}}, AnyHashable("UIKeyboardAnimationDurationUserInfoKey"): 0.25])
         */
        guard let rect = (n.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
            let duration = (n.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue
        else {
            return
        }
        
        let offset = view.bounds.height - rect.origin.y
        
        // 更新约束
        toolbarBottomCons.constant = offset
        
        //设置动画
        UIView.animate(withDuration:duration) {
            self.view.layoutIfNeeded()
        }
    }
}
// MARK: - UITextViewDelegate
extension JCLTestViewController:UITextViewDelegate {
    
    /// 发布按钮的开关监听
    ///
    /// - Parameter textView: textView是否有值
    func textViewDidChange(_ textView: UITextView) {
        
        commitBtn.isEnabled = textView.hasText
    }
}
